/*
 * @Author: jianfanfan 1217572833@qq.com
 * @Date: 2023-11-21 10:45:54
 * @LastEditors: jianfanfan 1217572833@qq.com
 * @LastEditTime: 2023-11-21 19:38:42
 * @FilePath: \nest-project\src\src\modules\login\login.service.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Injectable, BadRequestException } from '@nestjs/common';
import { CreateLoginDto } from './dto/create-login.dto';
import { UpdateLoginDto } from './dto/update-login.dto';
import { JwtService } from '@nestjs/jwt';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Login } from './entities/login.entity';
import * as bcrypt from 'bcrypt';

@Injectable()
export class LoginService {
  constructor(
    @InjectRepository(Login)
    private loginRepository: Repository<Login>,
    private readonly JwtService: JwtService,
  ) {}

  /**
   * 校验用户名、密码
   * @param username 用户名
   * @param password 密码
   * @returns user信息
   */
  async validateUser(username: string, password: string): Promise<any> {
    const user = await this.loginRepository.findOne({
      where: { username, password },
    });
    if (user && (await bcrypt.compare(password, user.password))) {
      return user;
    }
  }

  findAll(): Promise<Login[]> {
    return this.loginRepository.find();
  }

  findOne(id: number): Promise<Login | null> {
    return this.loginRepository.findOneBy({ id });
  }

  async remove(id: number): Promise<void> {
    await this.loginRepository.delete(id);
  }

  /**
   * 对密码进行加密
   * @param password
   * @returns
   */
  async hashPassword(password: string): Promise<string> {
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(password, saltRounds);
    return hashedPassword;
  }

  /**
   * 注册新用户
   * @param username
   * @param password
   * @returns
   */
  async createLogin(username: string, password: string): Promise<Login> {
    const hashedPassword = await this.hashPassword(password);

    const newUser = this.loginRepository.create({
      username,
      password: hashedPassword,
    });
    return this.loginRepository.save(newUser);
  }

  // 登录
  async login(loginData: CreateLoginDto) {
    const findUser = await this.loginRepository.findOne({
      where: { username: loginData.username },
    });
    // 没有找到
    if (!findUser) return new BadRequestException('用户不存在');

    // 找到了对比密码
    // const compareRes: boolean = bcryptjs.compareSync(
    //   loginData.password,
    //   findUser.password,
    // );
    // 密码不正确
    // if (!compareRes) return new BadRequestException('密码不正确');
    const payload = { username: findUser.username };

    return {
      token: this.JwtService.sign(payload),
      msg: '登录成功',
    };
  }
}
